package cn.kgc.springmvc.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/10/20
 * 全局异常处理类
 */
//@ControllerAdvice   //  全局异常处理类
@RestControllerAdvice  //  返回数据的格式统一使用json格式
public class GlobalExceptionHandler {

    //@ExceptionHandler(NullPointerException.class)
    //public String nullPointerExceptionHandler(Exception e){
    //    System.out.println("exception info : 空指针异常");
    //    return "error";
    //}


    //@ExceptionHandler(ArithmeticException.class)
    //public String arithmeticExceptionHandler(Exception e){
    //    System.out.println("exception info : 数学运算异常");
    //    return "error";
    //}


    @ExceptionHandler(ArithmeticException.class)
    //@ResponseBody
    public Map<String,Object> arithmeticExceptionHandler(Exception e){
        System.out.println("exception info : 数学运算异常");

        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "数学运算异常");
        return map;
    }


    // 处理文件上传的异常
    @ExceptionHandler(UploadException.class)
    public Map<String,Object>  uploadExceptionHandler(UploadException e){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg",e.getMessage());
        return map;
    }


}
